//
//  TwoViewController.m
//  Tongcheng
//
//  Created by   丛熠超 on 2017/4/5.
//  Copyright © 2017年 Tongcheng. All rights reserved.
//

#import "TwoViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "NearByOperator.h"
#import "AppDelegate.h"
#import "NearByDataModel.h"
#import "MJRefresh.h"
#import "SayHiOperator.h"
#import "PersonalViewController.h"

@interface TwoViewController ()<UITableViewDelegate, UITableViewDataSource,TWOTableViewDelegate,CLLocationManagerDelegate>
{
    CLLocationManager *localtionManger;
    CGFloat latitude;
    CGFloat longitude;
    NSString *Province;
    NSString *city;
    NSString *Street;
    BOOL isHaveLocation;
}
@property (weak, nonatomic) IBOutlet UITableView *NearbyTableView;
@property (weak, nonatomic) IBOutlet UIButton *SayHIToAll;

@property (nonatomic, strong) NSArray *dataArray;

@end

static NSString *mainCellIdentifier = @"MainTableViewCell";

@implementation TwoViewController

- (void)setDataArray:(NSArray *)dataArray
{
    _dataArray = dataArray;
    [self.NearbyTableView reloadData];
}

- (void)setupView
{
    _NearbyTableView.delegate = self;
    _NearbyTableView.dataSource = self;
    _NearbyTableView.tableFooterView = [[UIView alloc] init];
    
    _NearbyTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(GetData)];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
    [self locatemap];
    // Do any additional setup after loading the view from its nib.
}

- (void)locatemap {
    
    if ([CLLocationManager locationServicesEnabled]) {
        localtionManger = [[CLLocationManager alloc] init];
        localtionManger.delegate = self;
        [localtionManger requestAlwaysAuthorization];
        [localtionManger requestWhenInUseAuthorization];
        localtionManger.desiredAccuracy = kCLLocationAccuracyBest;
        localtionManger.distanceFilter = 5.0;
        [localtionManger startUpdatingLocation];
    }
    
}
//定位失败走这个方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"允许定位提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingURL];
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:ok];
    [alert addAction:cancle];
    [self presentViewController:alert animated:YES completion:nil];
}
//定位成功后
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [localtionManger stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    latitude = currentLocation.coordinate.latitude;
    longitude = currentLocation.coordinate.longitude;
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder  reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!isHaveLocation) {
            if (placemarks.count > 0) {
                CLPlacemark *placeMark = placemarks[0];
                city = placeMark.locality;
                Street = placeMark.thoroughfare;
                Province = placeMark.administrativeArea;
                isHaveLocation = YES;
                [self GetData];
            }
        }
    }];
    
   
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mainCellIdentifier];
    if (!cell)
    {
        cell = [[UINib nibWithNibName:@"TwoTableViewCell" bundle:nil] instantiateWithOwner:self options:nil].lastObject;
    }
    NearByListModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    cell.indexPath = indexPath;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    return cell;
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"go userInfo");
    PersonalViewController *personalVc = [[PersonalViewController alloc] init];
    NearByListModel *model = self.dataArray[indexPath.row];
    personalVc.navTitle = model.user_nicename;
    personalVc.userId = model._id;
    [self.navigationController pushViewController:personalVc animated:YES];
}

- (void)clickSayHiWith:(NearByListModel *)model withIndex:(NSIndexPath *)indexPath
{
    if (!model.hello) {
        [self sayHiWith:model.user_login withIndex:indexPath];
    }else{
        [self showToastMessage:@"你已经打过招呼了"];
    }
}

- (IBAction)SayHiToAll:(id)sender {
    NSMutableString *str = [NSMutableString string];
    for (NearByListModel *model in self.dataArray) {
        [str appendString:[NSString stringWithFormat:@"%@,",model.user_login]];
    }
    NSUInteger location = [str length]-1;
    NSRange range = NSMakeRange(location, 1);
    [str deleteCharactersInRange:range];
    [self sayHiWith:str withIndex:nil];
}

//网络请求
- (void)GetData {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = self.config.token;
    dic[@"user_id"] = self.config.userId;
    dic[@"lng"] = [NSString stringWithFormat:@"%f", longitude];
    dic[@"lat"] = [NSString stringWithFormat:@"%f", latitude];
    dic[@"Province"] = Province;
    dic[@"city"] = city;
    dic[@"Street"] = Street;
    dic[@"page"] = @"1";
    NearByOperator *operator = [[NearByOperator alloc] initWithParams:dic];
    [self.networkingManager asyncTaskOnVC:self operator:operator successBlock:^(BaseModel *baseModel) {
        [_NearbyTableView.mj_header endRefreshing];
        if ([baseModel.code isEqualToString:@"1"]) {
            self.dataArray = [NSMutableArray arrayWithArray:operator.data.data.list];
        }
        [_NearbyTableView reloadData];
    } failBlock:^(BaseModel *baseModel) {
        [_NearbyTableView.mj_header endRefreshing];
    }];
}

- (void)sayHiWith:(NSString *)userLogin withIndex:(NSIndexPath *)indexpath
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = self.config.token;
    dic[@"user_id"] = self.config.userId;
    dic[@"To_user_login"] = userLogin;
    dic[@"Content"] = @"hi 我很中意你，可以聊聊么?";
    SayHiOperator *operator = [[SayHiOperator alloc] initWithParams:dic];
    [self.networkingManager asyncTaskOnVC:self operator:operator successBlock:^(BaseModel *baseModel) {
        NSLog(@"%@", baseModel);
//        if ([baseModel.code isEqualToString:@"1"]) {
//            [self setupDataArrayWith:indexpath];
//        }
    } failBlock:^(BaseModel *baseModel) {
        
    }];
}

- (void)setupDataArrayWith:(NSIndexPath *)indexPath
{
    if (indexPath) {
        NearByListModel *model = self.dataArray[indexPath.row];
        model.hello = YES;
        [self.NearbyTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }else{
        for (NearByListModel *model in self.dataArray) {
            model.hello = YES;
        }
        [self.NearbyTableView reloadData];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
